#include "stdafx.h"
#include "models/config.h"
#include "poke_const.h"
#include "molecular_core.h"

Config::Config()
: m_nNowPos(0)
{
    PokeConfig oConfig = { NULL, 0, 0 };
    m_vConfigs.push_back(oConfig);
}

Config::~Config()
{

}

bool
Config::OnExecute(const M::AtomEndPoint &oSrcAtom, int nFuncId, void *pParams, void *pIOParams)
{
    bool bRet = false;
    switch(nFuncId) {
    case PFI_SET_CONFIG:
        bRet = OnSetConfig((PokeConfig *)pParams);
        break;
    case PFI_GET_CONFIG:
        bRet = OnGetConfig((PokeConfig *)pParams);
        break;
    case PFI_GET_CONFIG_CURSOR:
        bRet = OnGetConfigCursor((PokeConfigCursor *)pParams);
        break;
    case PFI_USE_PREV_CONFIG:
        bRet = OnUsePrevConfig(!!pParams);
        break;
    case PFI_USE_NEXT_CONFIG:
        bRet = OnUseNextConfig(!!pParams);
        break;
    }

    if(NULL != pIOParams) {
        (*(bool *)pIOParams) = bRet;
    }

    return bRet;
}

bool
Config::OnSetConfig(PokeConfig *pParams)
{
    if(NULL == pParams) {
        return false;
    }

    if(m_nNowPos >= m_vConfigs.size()) {
        m_nNowPos = m_vConfigs.size() - 1;
    }

    m_vConfigs.erase(m_vConfigs.begin() + m_nNowPos + 1, m_vConfigs.end());
    m_vConfigs.push_back(*pParams);
    m_nNowPos = m_vConfigs.size() - 1;
    
    FireEvent(PEI_UPDATE_MODEL, NULL);
    FireEvent(PEI_UPDATE_UI, NULL);

    return true;
}

bool
Config::OnGetConfig(PokeConfig *pParams)
{
    if(NULL == pParams) {
        return false;
    }

    if(m_nNowPos >= m_vConfigs.size()) {
        m_nNowPos = m_vConfigs.size() - 1;
    }

    *pParams = m_vConfigs[m_nNowPos];

    return true;
}

bool
Config::OnGetConfigCursor(PokeConfigCursor *pParams)
{
    if(NULL == pParams) {
        return false;
    }

    pParams->m_nNowPos = m_nNowPos;
    pParams->m_nConfigNum = m_vConfigs.size();

    return true;
}

bool
Config::OnUsePrevConfig(bool bUpdate)
{
    if(!(m_nNowPos > 0 && m_nNowPos < m_vConfigs.size())) {
        return false;
    }

    --m_nNowPos;

    if(bUpdate) {
        FireEvent(PEI_UPDATE_MODEL, NULL);
        FireEvent(PEI_UPDATE_UI, NULL);
    }

    return true;
}

bool
Config::OnUseNextConfig(bool bUpdate)
{
    if(!(m_nNowPos >= 0 && m_nNowPos < m_vConfigs.size() - 1)) {
        return false;
    }

    ++m_nNowPos;

    if(bUpdate) {
        FireEvent(PEI_UPDATE_MODEL, NULL);
        FireEvent(PEI_UPDATE_UI, NULL);
    }

    return true;
}